package com.ruoyi.tenant.controller;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.service.SysRegisterService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.tenant.domain.SysTenant;
import com.ruoyi.tenant.dto.RegisterDTO;
import com.ruoyi.tenant.service.IInitTableService;
import com.ruoyi.tenant.service.ISysTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/initdatabase")
public class tenantController extends BaseController {

    @Autowired
    private ISysTenantService iSysTenantService;

    @Autowired
    private IInitTableService iInitTableService;

    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;

    private static String PREFIX = "ry-vue-";
    private static String PREFIX_URL = "jdbc:mysql://localhost:3306/";
    private static String TAIL_URL = "?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true";

    @Value("${tenant.database.name}")
    private String name;

    @Value("${tenant.database.password}")
    private String password;

    public String databaseuuid;

    private static String REDISPREFIX = "registerTenant:";

    @PostMapping("/creat")
    public AjaxResult creatDatabase(@RequestBody RegisterDTO registerDTO){
        String tenatId = registerDTO.getTenantId().toLowerCase();
        if("master".equals(tenatId)){
            return AjaxResult.error("不允许创建管理空间");
        }
       SysTenant sysTenant = iSysTenantService.selectTenantByTenantId(tenatId);
       if(sysTenant != null){
           return AjaxResult.error("该租户已存在");
       }
       String ip = IpUtils.getIpAddr();
       Integer registerCount = redisCache.getCacheObject(REDISPREFIX+ip);
       if(registerCount==null) registerCount = 0;
       if(registerCount > 0){
           AsyncManager.me().execute(AsyncFactory.recordLogininfor("master",registerDTO.getUsername(), Constants.REGISTER,ip +"注册租户"+tenatId +"超上限" ));
           return AjaxResult.error("同一个ip 24小时内只能注册一个租户");
       }
        // 验证码开关
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(registerDTO.getUuid(), "");
            String captcha = redisCache.getCacheObject(verifyKey);
            if (captcha == null)
            {
                throw new CaptchaExpireException();
            }
            if (!registerDTO.getCode().equalsIgnoreCase(captcha))
            {
                throw new CaptchaException();
            }
        }

      iSysTenantService.createdatabase(PREFIX+tenatId);
       SysTenant newTenant=new SysTenant();
       newTenant.setCompanyName(registerDTO.getCompanyName());
       newTenant.setPrincipal(registerDTO.getPrincipal());
       newTenant.setProfession(registerDTO.getProfession());
       newTenant.setTelPhone(registerDTO.getTelPhone());
       newTenant.setTenantid(tenatId);
       newTenant.setUrl(PREFIX_URL+PREFIX+tenatId+TAIL_URL);
       newTenant.setUsername(name);
       newTenant.setPassword(password);
       newTenant.setState(0);
       newTenant.setCreateDate(new Date());
       RegisterDTO re = new RegisterDTO();
       re.setSuccess(false);
       if(iSysTenantService.insertSysTenant(newTenant) != 0){
           databaseuuid = UUID.fastUUID().toString();
           re.setSuccess(true);
           re.setDatabaseuuid(databaseuuid);
       }
       return AjaxResult.success(re);
    }

    @PostMapping("/inittable")
    public AjaxResult initTable(@RequestBody RegisterDTO registerDTO){

        //防止直接调用接口执行sql,先走生成数据库获得uuid再执行初始化
        if(StringUtils.isEmpty(registerDTO.getDatabaseuuid())){
            return AjaxResult.error("请求无uuid信息！");
        }
        if(!registerDTO.getDatabaseuuid().equals(databaseuuid)){
            return AjaxResult.error("不允许对已有数据库初始化！");
        }
        AjaxResult re = iInitTableService.initTable(registerDTO);

        RegisterBody registerBody = new RegisterBody();
        BeanUtils.copyBeanProp(registerBody,registerDTO);

        String msg = registerService.register(registerBody);

        String ip = IpUtils.getIpAddr();
        Integer registerCount = redisCache.getCacheObject(REDISPREFIX + ip);
        if(registerCount==null) registerCount = 0;
        registerCount = registerCount + 1;
        redisCache.setCacheObject(REDISPREFIX+ip,registerCount,1440, TimeUnit.MINUTES);

        return StringUtils.isEmpty(msg) ? success() : error(msg);

    }

}
